package com.cn.wanxi.common;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器
public class MyHandler implements HandlerInterceptor {
    //    执行方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//        System.out.println("preHandle");
        //        乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String url = req.getServletPath();
        System.out.println(url);
//        只有访问后台的连接以back开始的才需要登录
        if (url.startsWith("/back/")) {
            String loginName = req.getParameter("loginName");
            String username = (String) req.getSession().getAttribute(loginName);
            if (username == null) {
                resp.sendRedirect("/login.html");
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }

    }

    //
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle");
    }

    //    最后执行：销毁
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("afterCompletion");
    }
}
